package com.wy.authority.controller;

import com.wy.authority.entity.*;
import com.wy.authority.service.ConfigureService;
import com.wy.authority.service.MsgService;
import com.wy.authority.service.ProcurementService;
import com.wy.authority.service.UserService;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.commons.lang3.RandomStringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.xml.namespace.QName;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author 忘忧
 * @Date Created in 2021/2/1 15:15
 * @Description:
 */
@RestController
@RequestMapping("/proc")
public class ProcurementController {
    private final static String NAMESPACE = "http://tempuri.org/";

    private final static String endpoint = "http://115.29.52.221:24663/Service/?wsdl";

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private  UserService userService;

    @Autowired
    private ProcurementService procurementService;

    @Autowired
    private ConfigureService configureService;


    @Autowired
    private MsgService msgService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/findall")
    public List<Procurement> findall() {
        List<Procurement> list = procurementService.findall();
        return list;
    }

    //分页查询
    @GetMapping("/find_bynum")
    public Procurement find_bynum(@RequestParam(defaultValue = "1") Integer pagenum, @RequestParam(defaultValue = "6") Integer pagesize) {
        return procurementService.find_bynum(pagenum, pagesize);
    }

    //添加
    @PostMapping("/insert")
    public String insert(@RequestBody Procurement procurement) {
        //获取时间
        DateTimeFormatter time = DateTimeFormatter.ofPattern("yyyyMMddHH");
        String localDate = LocalDateTime.now().format(time);
        //随机数
        String randomNum = RandomStringUtils.randomNumeric(4);
        String order = "GC";
        String proc_order = order + localDate + randomNum;
        int proc_num = procurement.getProc_num();
        double proc_price = procurement.getProc_price();
        double total_price = proc_num * proc_price;
        procurement.setTotal_price(total_price);
        procurement.setProc_order(proc_order);
        procurement.setStatus("0");
        System.out.println(procurement);
        //开启流程
        HashMap<String, Object> map = new HashMap<>();
//        map.put("taskUser","shopper");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("procurement", map);
        System.out.println(processInstance.getId());
        procurement.setProcessid(processInstance.getId());
        Task tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        Task task = taskService.createTaskQuery().taskId(tasks.getId()).singleResult();

        if (task == null) {
            throw new RuntimeException("流程不存在");
        }
        map.put("proc_num", procurement.getProc_num());
        map.put("proc_order", procurement.getProc_order());//单号
        map.put("proc_type", procurement.getProc_type());//油品
        map.put("proc_buy", procurement.getProc_buy());//采购人
        map.put("proc_price", procurement.getProc_price());//价格
        map.put("total_price", procurement.getTotal_price());//金额
        map.put("proc_seller", procurement.getProc_seller());//卖方
        map.put("proc_people", procurement.getProc_people());//卖方联系人
        map.put("proc_phone", procurement.getProc_phone());//卖方联系电话
        map.put("proc_company", procurement.getProc_company());//买方
        map.put("proc_desc", procurement.getProc_desc());//采购说明
        map.put("arrival_time", procurement.getArrival_time());//到货日期
        map.put("create_time", procurement.getCreate_time());//采购日期
        map.put("status", procurement.getStatus());//状态
        map.put("processid", procurement.getProcessid());//流程id
        taskService.complete(tasks.getId(), map); //结束当前任务抛给下一个
        procurementService.insert(procurement);
        String power = redisTemplate.opsForValue().get("code"); //接受身份
        if (power.equals("shopper")) {
            String msg_name="部门消息";
            Configure configure= configureService.find_basic(msg_name);
               String  [] receiver= configure.getReceiver_ids().split(",");
                for (int i = 0; i < receiver.length; i++) {
                    System.out.println(receiver[i]);
                    SysUser sysUser = userService.sysuser(receiver[i]);
                    if(configure.getMobile().equals("mobile")) {
                        String code = sysUser.getNick_name();
                        System.out.println("----------------------------");
                        String mobileNum = sysUser.getPhonenumber();
                        String content = code + ",您好!有新的报价单需要您的审批，请您尽快审批。询价单编号:" + procurement.getProc_order() + "。【易见源科技】";
//            System.out.println(SubmitSms("yidongquan", "yidongquan@#123", mobileNum, content, "1001"));
                        Msg msg = new Msg();
                        msg.setMsg_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                        msg.setMsg_order(proc_order);
                        msg.setMsg_people(code);
                        msg.setMsg_status("0");
                        msg.setMsg_content(content);
                        msgService.insertmsg(msg);
                    }
                    if(configure.getApp().equals("app")){
                        System.out.println("发送短信详细");
                    }

            }
        }

//        String code=redisTemplate.opsForValue().get("code1");
//        String mobileNum = redisTemplate.opsForValue().get("phonenumber");
//        String content = code+",您好!有新的报价单需要您的审批，请您尽快审批。询价单编号:"+procurement.getProc_order()+ "。【易见源科技】";
//            System.out.println(SubmitSms("yidongquan", "yidongquan@#123", mobileNum, content, "1001"));

        return "success";
    }

//    //模糊查询
//    @ResponseBody
//    @GetMapping("/selectby_ord")
//    public List<Procurement> selectby_ord() {
//        List<Procurement> list = procurementService.selectby_ord();
//        return list;
//    }

    @GetMapping("/test")
    public List<Map<String, Object>> test() {
        String power = redisTemplate.opsForValue().get("code"); //接受身份
        TaskService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup(power).list();
        List<ProcessInstance> pis = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey("procurement").list();
        System.out.println("你有 " + tasks.size() + " 个待办任务:");
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < tasks.size(); i++) {
            System.out.println((i + 1) + ") " + tasks.get(i).getName() + tasks.get(i).getId());
            Map<String, Object> processVariables = taskService.getVariables(tasks.get(i).getId());
            System.out.println(processVariables);
            Map<String, Object> map = new LinkedHashMap<>();
            String status = null;
            if (processVariables.get("status").equals("0")) {
                status = "进行中";
            }
            if (processVariables.get("status").equals("1")) {
                status = "已完成";
            }
            map.put("taskid", tasks.get(i).getId());//任务id
            map.put("proc_num", processVariables.get("proc_num"));//采购数量
            map.put("proc_order", processVariables.get("proc_order"));//单号
            map.put("proc_type", processVariables.get("proc_type"));//油品
            map.put("proc_buy", processVariables.get("proc_buy"));//采购人
            map.put("proc_price", processVariables.get("proc_price"));//价格
            map.put("total_price", processVariables.get("total_price"));//金额
            map.put("proc_seller", processVariables.get("proc_seller"));//卖方
            map.put("proc_people", processVariables.get("proc_people"));//卖方联系人
            map.put("proc_phone", processVariables.get("proc_phone"));//卖方联系电话
            map.put("proc_company", processVariables.get("proc_company"));//买方
            map.put("proc_desc", processVariables.get("proc_desc"));//采购说明
            map.put("arrival_time", processVariables.get("arrival_time"));//到货日期
            map.put("create_time", processVariables.get("create_time"));//采购日期
            map.put("status", status);//状态
            map.put("processid", processVariables.get("processid"));//流程id
            list.add(map);
            System.out.println(tasks.get(i).getId());
        }
        System.out.println(pis);
        return list;
    }

    //审核
    @PostMapping("/apply")
    public void approved(@RequestBody Reason reason) throws Exception {
        System.out.println(reason.getTask_id() + reason.getIdeas() + reason.getReason() + reason.getNumber() + reason.getProc_order());
        Task task = taskService.createTaskQuery().taskId(reason.getTask_id()).singleResult();
        String power = redisTemplate.opsForValue().get("code");
        String targetTaskKey = null;
        String targetTaskKeys = null;
        if (power.equals("dept")) {
            targetTaskKey = "sid-2F0821C2-FCA7-415E-AF04-CC08AF30EEC6";
        }
        if (power.equals("finance")) {
            targetTaskKey = "sid-729D7690-C07A-486C-9B45-DE54BEBB54AE";
        }
        if (power.equals("presidents")) {
            targetTaskKey = "sid-3A378D45-888B-4F2E-A477-B77B68ACDF5D";
        }
        if (power.equals("president")) {
            targetTaskKey = "sid-5AA79E6A-B400-47D5-9163-DC44CEE0EA32";
        }
        if (task == null) {
            throw new RuntimeException("流程不存在");
        }
        if (reason.getReason().equals("同意")) {
            //通过审核
            HashMap<String, Object> map = new HashMap<>();
            map.put("reason", reason.getReason());
            map.put("ideas", reason.getIdeas());
            map.put("number", reason.getNumber());
            taskService.complete(reason.getTask_id(), map);
            //发送短信
            if (power.equals("dept")) {
                String msg_name = "财务部消息";
                Configure configure = configureService.find_basic(msg_name);
                String[] receiver = configure.getReceiver_ids().split(",");
                for (int i = 0; i < receiver.length; i++) {
                    System.out.println(receiver[i]);
                    SysUser sysUser = userService.sysuser(receiver[i]);
                    if (configure.getMobile().equals("mobile")) {
                        String code = sysUser.getNick_name();
                        System.out.println("----------------------------");
                        String mobileNum = sysUser.getPhonenumber();
                        String content = code + ",您好!有新的报价单需要您的审批，请您尽快审批。询价单编号:" + reason.getProc_order() + "。【易见源科技】";
//            System.out.println(SubmitSms("yidongquan", "yidongquan@#123", mobileNum, content, "1001"));
                        Msg msg = new Msg();
                        msg.setMsg_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                        msg.setMsg_order(reason.getProc_order());
                        msg.setMsg_people(code);
                        msg.setMsg_status("0");
                        msg.setMsg_content(content);
                        msgService.insertmsg(msg);
                    }
                    if (configure.getApp().equals("app")) {
                        System.out.println("发送短信详细");
                    }

                }
            }
            if (power.equals("finance")) {
                String msg_name = "副总经理消息";
                Configure configure = configureService.find_basic(msg_name);
                String[] receiver = configure.getReceiver_ids().split(",");
                for (int i = 0; i < receiver.length; i++) {
                    System.out.println(receiver[i]);
                    SysUser sysUser = userService.sysuser(receiver[i]);
                    if (configure.getMobile().equals("mobile")) {
                        String code = sysUser.getNick_name();
                        System.out.println("----------------------------");
                        String mobileNum = sysUser.getPhonenumber();
                        String content = code + ",您好!有新的报价单需要您的审批，请您尽快审批。询价单编号:" + reason.getProc_order() + "。【易见源科技】";
//            System.out.println(SubmitSms("yidongquan", "yidongquan@#123", mobileNum, content, "1001"));
                        Msg msg = new Msg();
                        msg.setMsg_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                        msg.setMsg_order(reason.getProc_order());
                        msg.setMsg_people(code);
                        msg.setMsg_status("0");
                        msg.setMsg_content(content);
                        msgService.insertmsg(msg);
                    }
                    if (configure.getApp().equals("app")) {
                        System.out.println("发送短信详细");
                    }

                }
            }
            if (power.equals("presidents") && Integer.parseInt(reason.getNumber()) < 100) {
                Procurement procurement = new Procurement();
                procurement.setProc_order(reason.getProc_order());
                procurement.setStatus("1");
                procurementService.update2(procurement);
                String msg_name = "副总经理消息";
                Configure configure = configureService.find_basic(msg_name);
                String[] receiver = configure.getReceiver_ids().split(",");
                for (int i = 0; i < receiver.length; i++) {
                    System.out.println(receiver[i]);
                    SysUser sysUser = userService.sysuser(receiver[i]);
                    if (configure.getMobile().equals("mobile")) {
                        String code = sysUser.getNick_name();
                        System.out.println("----------------------------");
                        String mobileNum = sysUser.getPhonenumber();
                        String content1 = code + ",您好!询价单编号:" + reason.getProc_order() + ",已完成全部审批。【易见源科技】";
//            System.out.println(SubmitSms("yidongquan", "yidongquan@#123", mobileNum, content, "1001"));
                        Msg msg = new Msg();
                        msg.setMsg_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                        msg.setMsg_order(reason.getProc_order());
                        msg.setMsg_people(code);
                        msg.setMsg_status("1");
                        msg.setMsg_content(content1);
                        msgService.insertmsg(msg);
                    }
                    if (configure.getApp().equals("app")) {
                        System.out.println("发送短信详细");
                    }

                }
            }
            if (power.equals("presidents") && Integer.parseInt(reason.getNumber()) > 100) {
                String msg_name = "总经理消息";
                Configure configure = configureService.find_basic(msg_name);
                String[] receiver = configure.getReceiver_ids().split(",");
                for (int i = 0; i < receiver.length; i++) {
                    System.out.println(receiver[i]);
                    SysUser sysUser = userService.sysuser(receiver[i]);
                    if (configure.getMobile().equals("mobile")) {
                        String code = sysUser.getNick_name();
                        System.out.println("----------------------------");
                        String mobileNum = sysUser.getPhonenumber();
                        String content = code + ",您好!有新的报价单需要您的审批，请您尽快审批。询价单编号:" + reason.getProc_order() + "。【易见源科技】";
//            System.out.println(SubmitSms("yidongquan", "yidongquan@#123", mobileNum, content, "1001"));
                        Msg msg = new Msg();
                        msg.setMsg_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                        msg.setMsg_order(reason.getProc_order());
                        msg.setMsg_people(code);
                        msg.setMsg_status("0");
                        msg.setMsg_content(content);
                        msgService.insertmsg(msg);
                    }
                    if (configure.getApp().equals("app")) {
                        System.out.println("发送短信详细");
                    }

                }
            }
            if (power.equals("president")) {
                Procurement procurement = new Procurement();
                procurement.setProc_order(reason.getProc_order());
                procurement.setStatus("1");
                procurementService.update2(procurement);
                String msg_name = "总经理消息";
                Configure configure = configureService.find_basic(msg_name);
                String[] receiver = configure.getReceiver_ids().split(",");
                for (int i = 0; i < receiver.length; i++) {
                    System.out.println(receiver[i]);
                    SysUser sysUser = userService.sysuser(receiver[i]);
                    if (configure.getMobile().equals("mobile")) {
                        String code = sysUser.getNick_name();
                        System.out.println("----------------------------");
                        String mobileNum = sysUser.getPhonenumber();
                        String content1 = code + ",您好!询价单编号:" + reason.getProc_order() + ",已完成全部审批。【易见源科技】";
//            System.out.println(SubmitSms("yidongquan", "yidongquan@#123", mobileNum, content, "1001"));
                        Msg msg = new Msg();
                        msg.setMsg_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                        msg.setMsg_order(reason.getProc_order());
                        msg.setMsg_people(code);
                        msg.setMsg_status("1");
                        msg.setMsg_content(content1);
                        msgService.insertmsg(msg);
                    }
                    if (configure.getApp().equals("app")) {
                        System.out.println("发送短信详细");
                    }

                }
            }
//            String code=redisTemplate.opsForValue().get("code1");
//            String proc_order =reason.getProc_order();
//            String mobileNum = redisTemplate.opsForValue().get("phonenumber");
//            String content = code+",您好!有新的报价单需要您的审批，请您尽快审批。询价单编号:"+proc_order+ "。【易见源科技】";
//            System.out.println(SubmitSms("yidongquan", "yidongquan@#123", mobileNum, content, "1001"));

//            if(power.equals("president")){
//                String content1 = code+",您好!询价单编号:"+proc_order+ ",已完成全部审批。【易见源科技】";
//                Msg msg =new Msg();
//                msg.setMsg_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
//                msg.setMsg_order(proc_order);
//                msg.setMsg_people(code);
//                msg.setMsg_status("0");
//                msg.setMsg_content(content1);
//                msgService.insertmsg(msg);
//            }
//            Msg msg =new Msg();
//            msg.setMsg_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
//            msg.setMsg_order(proc_order);
//            msg.setMsg_people(code);
//            msg.setMsg_status("0");
//            msg.setMsg_content(content);
//            msgService.insertmsg(msg);
//            if (power.equals("president")) {
//                Procurement procurement = new Procurement();
//                procurement.setProc_order(reason.getProc_order());
//                procurement.setStatus("1");
//                procurementService.update2(procurement);
//                Msg msg1 =new Msg();
//                msg1.setMsg_order(reason.getProc_order());
//                msg1.setMsg_status("1");
//                msgService.update(msg1);
//            } else if (power.equals("presidents") && Integer.parseInt(reason.getNumber()) < 100) {
//                Procurement procurement = new Procurement();
//                procurement.setProc_order(reason.getProc_order());
//                procurement.setStatus("1");
//                procurementService.update2(procurement);
//                Msg msg2 =new Msg();
//                msg2.setMsg_order(reason.getProc_order());
//                msg2.setMsg_status("1");
//                msgService.update(msg2);
//            }
            if (reason.getReason().equals("不同意")) {
                Task currentTask = taskService.createTaskQuery().taskId(task.getId()).singleResult();
                if (currentTask == null) {
                    throw new Exception("当前任务节点不存在");
                }
                List<String> currentTaskKeys = new ArrayList<>();
                currentTaskKeys.add(currentTask.getTaskDefinitionKey());
                System.out.println(currentTaskKeys);
                runtimeService.createChangeActivityStateBuilder()
                        .processInstanceId(currentTask.getProcessInstanceId())
                        .moveActivityIdsToSingleActivityId(currentTaskKeys, targetTaskKey)
                        .changeState();
            }
        }
    }

    //转办
    @PostMapping("/zhuangban")
    public String zhuangban(@RequestBody Reason reason) throws Exception {
        Task task = taskService.createTaskQuery().taskId(reason.getTask_id()).singleResult();
        Task currentTask = taskService.createTaskQuery().taskId(task.getId()).singleResult();
        System.out.println(currentTask);
        if (currentTask == null) {
            throw new Exception("当前任务节点不存在");
        }
        List<String> currentTaskKeys = new ArrayList<>();
        currentTaskKeys.add(currentTask.getTaskDefinitionKey());
        System.out.println(currentTaskKeys);
        runtimeService.createChangeActivityStateBuilder()
                .processInstanceId(currentTask.getProcessInstanceId())
                .moveActivityIdsToSingleActivityId(currentTaskKeys,reason.getTargetTaskKey())
                .changeState();
        return "转办成功";
    }

    //修改
    @PutMapping("/update")
    public String update(@RequestBody Procurement procurement){
        procurementService.update(procurement);
        return "success";
    }
    //删除
    @DeleteMapping("/delete/{proc_id}")
    public void delete(@PathVariable("proc_id") Integer proc_id){
       procurementService.delete(proc_id);
    }


    /**
     * 生成流程图
     *
     * @param processId 任务ID
     */
    @RequestMapping(value = "processDiagram")
    public String genProcessDiagram(HttpServletResponse httpServletResponse, String processId) throws Exception {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();

        //流程走完的不显示图
        if (pi == null) {
            return "流程已全部审批";
        }
        Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();
        //使用流程实例ID，查询正在执行的执行对象表，返回流程实例对象
        String InstanceId = task.getProcessInstanceId();
        List<Execution> executions = runtimeService
                .createExecutionQuery()
                .processInstanceId(InstanceId)
                .list();

        //得到正在执行的Activity的Id
        List<String> activityIds = new ArrayList<>();
        List<String> flows = new ArrayList<>();
        for (Execution exe : executions) {
            List<String> ids = runtimeService.getActiveActivityIds(exe.getId());
            activityIds.addAll(ids);
        }

        //获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
        ProcessEngineConfiguration engconf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator diagramGenerator = engconf.getProcessDiagramGenerator();
        InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engconf.getActivityFontName(), engconf.getLabelFontName(), engconf.getAnnotationFontName(), engconf.getClassLoader(), 1.0);
        OutputStream out = null;
        byte[] buf = new byte[1024];
        int legth = 0;
        try {
            out = httpServletResponse.getOutputStream();
            while ((legth = in.read(buf)) != -1) {
                out.write(buf, 0, legth);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
        return "success";
    }

    public static String SubmitSms(String username, String password,
                                   String mobileNum, String content, String productNum) {

        String result = "";

        try {

            Service service = new Service();

            Call call = (Call) service.createCall();

            String soapActionURI = "http://tempuri.org/I_Order/SubmitSms";

            call.setUseSOAPAction(true);

            call.setSOAPActionURI(soapActionURI);

            call.setTargetEndpointAddress(endpoint);

            call.setOperationName(new QName(NAMESPACE, "SubmitSms"));// wsdl里面描述的接口名称

            call.addParameter(new QName(NAMESPACE, "username"),
                    org.apache.axis.encoding.XMLType.XSD_DATE,

                    javax.xml.rpc.ParameterMode.IN);// 接口的参数

            call.addParameter(new QName(NAMESPACE, "password"),
                    org.apache.axis.encoding.XMLType.XSD_DATE,

                    javax.xml.rpc.ParameterMode.IN);// 接口的参数

            call.addParameter(new QName(NAMESPACE, "mobileNum"),
                    org.apache.axis.encoding.XMLType.XSD_DATE,

                    javax.xml.rpc.ParameterMode.IN);// 接口的参数

            call.addParameter(new QName(NAMESPACE, "content"),
                    org.apache.axis.encoding.XMLType.XSD_DATE,

                    javax.xml.rpc.ParameterMode.IN);// 接口的参数

            call.addParameter(new QName(NAMESPACE, "productNum"),
                    org.apache.axis.encoding.XMLType.XSD_DATE,

                    javax.xml.rpc.ParameterMode.IN);// 接口的参数

            call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型

            result = (String) call.invoke(new Object[] { username, password,
                    mobileNum, content, productNum });

            // 给方法传递参数，并且调用方法

        }

        catch (Exception e) {

            System.err.println(e.toString());

        }

        return result;

    }


}
